import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookies_to_redis(request,user,response):
    """
    登录后，合并cookies购物车数据到redis数据库
    :param request: 本次请求对象，获取cookies中的购物车数据
    :param user: 登录用户数据,获取user_id
    :param response: 本次响应对象，清楚cookies的购物车数据
    :return:
    """
    # 获取
    cookies_cart_str = request.COOKIES.get('carts')

    # 没有数据直接返回响应
    if not cookies_cart_str:
        return response
    cookies_cart_dict = pickle.loads(base64.b64decode(cookies_cart_str.encode()))

    new_cart_dict = {}
    new_cart_selected_add = []
    new_cart_selected_remove = []

    # 同步cookies中的数据
    for sku_id,cookie_dict in cookies_cart_dict.items():
        new_cart_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            new_cart_selected_add.append(sku_id)
        else:
            new_cart_selected_remove.append(sku_id)
    # 写入到redis数据库
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    # new_cart_dict同步
    pl.hmset('carts_%s' % user.id,new_cart_dict)
    # 勾选状态同步
    if new_cart_selected_add:
        pl.sadd('selected_%s' % user.id,*new_cart_selected_add)
    if new_cart_selected_remove:
        pl.srem('selected_%s' % user.id,*new_cart_selected_remove)
    pl.execute()
    response.delete_cookie('carts')
    return response